package com.zbcz.crm.network

import com.zbcz.crm.CrmApplication
import com.zbcz.crm.sp.SharedPreferencesManager
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

object RetrofitManager {

    var BASE_URL = "39.100.83.212"
    val PORT = "9991"

//    var BASE_URL = "192.168.1.156"
//    val PORT = "9991"

    val mHashMap = HashMap<String, Retrofit>()

    // 创建一个信任所有证书的 TrustManager
    val trustAllCerts = arrayOf<TrustManager>(
        object : X509TrustManager {
            override fun checkClientTrusted(
                chain: Array<java.security.cert.X509Certificate>,
                authType: String
            ) {
            }

            override fun checkServerTrusted(
                chain: Array<java.security.cert.X509Certificate>,
                authType: String
            ) {
            }

            override fun getAcceptedIssuers(): Array<java.security.cert.X509Certificate> {
                return arrayOf()
            }
        }
    )

    val trustAllSslContext = SSLContext.getInstance("SSL").apply {
        init(null, trustAllCerts, java.security.SecureRandom())
    }


    private fun getOkHttpClient(): OkHttpClient {
        return getBaseOkHttpClientBuilder().build()
    }


    private fun getBaseOkHttpClientBuilder(): OkHttpClient.Builder {
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY // 设置日志级别
        return OkHttpClient.Builder()
            .sslSocketFactory(
                trustAllSslContext.socketFactory,
                trustAllCerts[0] as X509TrustManager
            )
            .hostnameVerifier { _, _ -> true }
            .addInterceptor(HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.BODY
            })
            .addInterceptor(loggingInterceptor) // 添加日志拦截器
            .addInterceptor(HeaderInterceptor())
        // 可以添加其他的拦截器或配置，比如超时时间等
    }

    private var mRetrofit: Retrofit? = null

    fun getRetrofit(): Retrofit {
        if (mRetrofit == null) {
            BASE_URL = createBaseUrl(BASE_URL, PORT)
            mRetrofit = Retrofit.Builder()
                .baseUrl(BASE_URL) // 设置你的 API base URL
                .addConverterFactory(GsonConverterFactory.create()) // 使用 Gson 作为数据转换器
                //.addCallAdapterFactory(CoroutineCallAdapterFactory())
                .client(getOkHttpClient()) // 设置自定义的 OkHttp 客户端
                .build().apply {
                    mHashMap[BASE_URL] = this
                }
        }
        return mRetrofit!!
    }


    fun createBaseUrl(serverAddress: String?, serverPort: String?): String {
        return "http://$serverAddress:$serverPort/"
    }

    class HeaderInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
            val originalRequest: Request = chain.request()

            // 添加自定义的 Header
            val modifiedRequest: Request = originalRequest.newBuilder()
                .header(
                    "token",
                    SharedPreferencesManager.getToken(CrmApplication.mApplication) ?: ""
                )
                .build()

            return chain.proceed(modifiedRequest)
        }
    }

    fun getImageUrl(imageAddress: String): String {
        return BASE_URL + "jeecg-boot/sys/common/static/" + imageAddress + "?token=" + SharedPreferencesManager.getToken(
            CrmApplication.mApplication
        )
    }
}